﻿using SharPy.Common;
using SharPy.DataModel;
using SharPy.File_Management;
using SharPy.GameObjects;
using SharPy.GameSettings;
using SharPy.Interface;
using SharPy.WebObjects;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Navigation;

namespace SharPy
{
    public partial class MainPage
    {
        private NavigationHelper navigationHelper;
        private ObservableDictionary defaultViewModel = new ObservableDictionary();
        StorageFile gameList;
        DataItem SelectedGame;

        /// <summary>
        /// Gets the view model for this <see cref="Page"/>.
        /// This can be changed to a strongly typed view model.
        /// </summary>
        public ObservableDictionary DefaultViewModel
        {
            get { return this.defaultViewModel; }
        }

        public void InitPage()
        {
            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += this.NavigationHelper_LoadState;
            this.navigationHelper.SaveState += this.NavigationHelper_SaveState;

            this.DefaultViewModel["Log"] = "Log here" + Environment.NewLine;
            this.DefaultViewModel["Title"] = "SharPy " + SharPy.DataModel.DataAbout.GetVersion().Result;
            this.DefaultViewModel["AboutText"] = SharPy.DataModel.DataAbout.GetDataAsync().Result;
        }

        #region Buttons
        private async void Refresh_Click(object sender, RoutedEventArgs e)
        {
            clDownloadHelper DownloadHelper = new clDownloadHelper();
            DownloadHelper.SetStatus += LogStatus;

            gameList = await DownloadHelper.StartDownload(false, SharPy.DataModel.DataAbout.GetGameListLink(), "gameList.txt", false);

            if (gameList != null)
            {
                clSettings.saveGameList(gameList);
                LogStatus("getting xml data", "");
                clXmlHandler xmlHandler = new clXmlHandler();
                string xmlData = await xmlHandler.getXmlFromFile(gameList);
                try
                {
                    List<clGameInfo> gameInfo = new List<clGameInfo>(await xmlHandler.getGameInfo(xmlData));
                }
                catch (System.Xml.XmlException)
                {
                    LogStatus("xml parsing error!", "failure");
                    return;
                }
                LogStatus("xml data loaded", "success");

                var eDataGroup = await DataSource.GetGroupAsync("Group1");
                this.DefaultViewModel["gameItems"] = eDataGroup;
            }
            else
                LogStatus("Problem retrieving game list", "");

        }

        private async void ItemView_ItemClick(object sender, ItemClickEventArgs ic)
        {
            this.SelectedGame = ic.ClickedItem as DataItem;
            this.DefaultViewModel["SelectedGame"] = SelectedGame.Title;
            FlyoutBase.ShowAttachedFlyout(((FrameworkElement)sender));
        }

        private async void Download_Click(object sender, RoutedEventArgs e)
        {
            DataItem b = this.SelectedGame;
            int g = await StartDownloadedGame(b.Title);
            if (g == 0)
            {
                Interface.clDialogs.Error("Please wait till download finishes, the game will start.", "In progress...");
                clDownloadHelper DownloadHelper = new clDownloadHelper();
                DownloadHelper.SetStatus += LogStatus;
                await DownloadHelper.StartDownload(false, b.Content, b.Title + ".zip");
                StartDownloadedGame(b.Title);
            }
        }

        private async void Delete_Click(object sender, RoutedEventArgs e)
        {
            DataItem b = this.SelectedGame;
            File_Management.clFileHelper.DeleteGame(b.Title);
        }

        private async void Restart_Click(object sender, RoutedEventArgs e)
        {
            DataItem b = this.SelectedGame;
            int g = await StartDownloadedGame(b.Title);
            if (g == 0)
                await SharPy.Interface.clDialogs.Error("Download the game, please.");
        }

        private async void LocalGame_Click(object sender, RoutedEventArgs e)
        {
            clPickerHelper PickerHelper = new clPickerHelper();
            var a = await PickerHelper.PickFolderAsync();

            if (a != null)
            {
                clGame CurrentGame = new clGame();
                await CurrentGame.RegisterGame(a);
                Frame.Navigate(typeof(GamePage), CurrentGame);
            }
        }

        private async void RestartLastGame(object sender, RoutedEventArgs e)
        {
            try
            {
                StorageFolder folder = await clSettings.getFolder();
                if (folder != null)
                {
                    clGame CurrentGame = new clGame();
                    await CurrentGame.RegisterGame(folder);

                    Frame.Navigate(typeof(GamePage), CurrentGame);
                }
            }
            catch (Exception exp)
            {
                clDialogs.Error(exp.Message, "Cannot find last game!");
            }
        }

        private async void ContinueLastGame(object sender, RoutedEventArgs e)
        {
            try
            {
                StorageFolder folder = await clSettings.getFolder();
                if (folder != null)
                {
                    clGame CurrentGame = new clGame();
                    await CurrentGame.RegisterGame(folder);
                    Frame.Navigate(typeof(GamePage), CurrentGame);
                }
            }
            catch (Exception exp)
            {
                clDialogs.Error(exp.Message, "Cannot find last game!");
            }
        }

        #endregion

        #region Methods
        private async Task<int> StartDownloadedGame(string game, bool restart = false)
        {
            try
            {
                StorageFolder pFolder = await (await ApplicationData.Current.RoamingFolder.GetFolderAsync("Downloads")).GetFolderAsync(game);
                clGame CurrentGame = new clGame();
                await CurrentGame.RegisterGame(pFolder);

                if (restart)
                    CurrentGame.LineNoHolder = 0;

                Frame.Navigate(typeof(GamePage), CurrentGame);
                return 1;
            }
            catch (FileNotFoundException)
            {
                return 0;
            }
        }

        private void LogStatus(object sender, DownloaderStatus e)
        {
            this.DefaultViewModel["Log"] += Environment.NewLine + e.sTitle + "   " + e.sMessage;
        }
        private void LogStatus(string e, string s)
        {
            this.DefaultViewModel["Log"] += Environment.NewLine + e + "   " + s;
        }

        #endregion

        #region NavigationHelper registration
        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="sender">
        /// The source of the event; typically <see cref="NavigationHelper"/>
        /// </param>
        /// <param name="e">Event data that provides both the navigation parameter passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
        /// a dictionary of state preserved by this page during an earlier
        /// session.  The state will be null the first time a page is visited.</param>
        private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            var eDataGroup = await DataSource.GetGroupAsync("Group1");
            if (eDataGroup == null)
            {
                if (await SharPy.Interface.clDialogs.RefreshGameList())
                    Refresh_Click(null, null);
            }
            this.DefaultViewModel["gameItems"] = eDataGroup;
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="sender">The source of the event; typically <see cref="NavigationHelper"/></param>
        /// <param name="e">Event data that provides an empty dictionary to be populated with
        /// serializable state.</param>
        private void NavigationHelper_SaveState(object sender, SaveStateEventArgs e)
        {
        }


        /// <summary>
        /// Gets the <see cref="NavigationHelper"/> associated with this <see cref="Page"/>.
        /// </summary>
        public NavigationHelper NavigationHelper
        {
            get { return this.navigationHelper; }
        }
        /// <summary>
        /// The methods provided in this section are simply used to allow
        /// NavigationHelper to respond to the page's navigation methods.
        /// <para>
        /// Page specific logic should be placed in event handlers for the  
        /// <see cref="NavigationHelper.LoadState"/>
        /// and <see cref="NavigationHelper.SaveState"/>.
        /// The navigation parameter is available in the LoadState method 
        /// in addition to page state preserved during an earlier session.
        /// </para>
        /// </summary>
        /// <param name="e">Provides data for navigation methods and event
        /// handlers that cannot cancel the navigation request.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedFrom(e);
        }

        #endregion

    }
}
